<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/9/18
 * Time: 下午1:35
 */

namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AdminOperationRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\Configure;

class ConfigureController extends Controller
{
    public function index()
    {
         \Request::merge([
             'configure' => Configure::get()
         ]);

        return view('main::configure', \Request::all());
    }

    public function update(Request $request)
    {
        try {
            $data = $request->input('data');

            if (!$data) {
                return fail(400, '表单填写不全');
            }

            foreach ($data as $item) {
                $res = Configure::where('cfg_key', $item['cfg_key'])->first();
                if (!$res) {
                    continue;
                }
                $res->cfg_value = $item['cfg_value'];
                $res->save();
            }

            return success();
        } catch (\Exception $e) {
            Log::error($e);
            return fail(500, '   系统错误');
        }
    }

    public function record(Request $request)
    {
        return view('main::admin_operation_record',\Request::all());
    }

    public function searchRecord(Request $request)
    {
        $data = [];
        $limit  = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $datetime = $request->input('datetime');
        $query = AdminOperationRecord::query();
        if ($datetime && isset($datetime[0]) && isset($datetime[1])) {
            $query->whereBetween('created_at', $datetime);
        }
        $data['total'] = $query->count();
        $res           = $query->take($limit)->skip($offset)->orderBy('id', 'desc')->get();

        $data['items'] = [];
        foreach ($res as $item) {
            $_item = $item->toArray();

            $data['items'][] = $_item;
        }
        return success($data);
    }
}